package com.weiyin.examination.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.weiyin.examination.R;
import com.weiyin.examination.http.DataService;
import com.weiyin.examination.http.HttpRequestListener;
import com.weiyin.examination.http.RetrofitClient;
import com.weiyin.examination.util.AudioRecoderUtils;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;

import java.io.File;
import java.io.IOException;

import okhttp3.ResponseBody;

public class RecordActivity extends BaseActivity implements View.OnClickListener, HttpRequestListener<ResponseBody> {
    private TextView audioYes, audioNo, audioContent;

    private RelativeLayout relativeLayout, image_RL;
    private AudioRecoderUtils mAudioRecoderUtils;
    private ImageView image;

    private AnimationDrawable animationDrawable;
    private MediaPlayer mediaPlayer;
    static final int VOICE_REQUEST_CODE = 66;

    private DataService dataService;

    private Handler mHandler = new Handler();
    @Override
    protected void onDestroy() {

        mediaPlayerStop();
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_test);
        LayoutHelper layoutHelper = new LayoutHelper(this);
        layoutHelper.scaleView(findViewById(R.id.audio_layout));
        dataService = new DataService(RetrofitClient.getInstance(this).getService());
        initView();
    }

    private void initView() {

        mediaPlayer = new MediaPlayer();
        image_RL = (RelativeLayout) findViewById(R.id.image_RL);
        audioContent = (TextView) findViewById(R.id.audioContent);
        audioYes = (TextView) findViewById(R.id.audioYes);
        audioNo = (TextView) findViewById(R.id.audioNo);
        image = (ImageView) findViewById(R.id.image);
        audioContent.setText("你是否可以清晰分辨你自己的声音？");
        relativeLayout = (RelativeLayout) findViewById(R.id.audioRlPlay);

        relativeLayout.setVisibility(View.GONE);

        audioNo.setOnClickListener(this);
        audioYes.setOnClickListener(this);


        mAudioRecoderUtils = new AudioRecoderUtils();

        //录音回调
        mAudioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {

            //录音中....db为声音分贝，time为录音时长
            @Override
            public void onUpdate(double db, long time) {
            }

            //录音结束，filePath为保存路径
            @Override
            public void onStop(final String filePath) {
                try {
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(filePath);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


        //6.0以上需要权限申请
        requestPermissions();

    }

    /**
     * 开启扫描之前判断权限是否打开
     */
    private void requestPermissions() {
        //判断是否开启摄像头权限
        if ((ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) &&
                (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
                ) {
            StartListener();

            //判断是否开启语音权限
        } else {
            //请求获取摄像头权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, VOICE_REQUEST_CODE);
        }

    }

    /**
     * 请求权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == VOICE_REQUEST_CODE) {
            if ((grantResults[0] == PackageManager.PERMISSION_GRANTED) && (grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                StartListener();
            } else {
                Toast.makeText(this, "已拒绝权限！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void mediaPlayerStop() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
        }
        if (animationDrawable != null) {
            animationDrawable.stop();
            image.setImageResource(R.drawable.item1);
        }
    }

    boolean onclick = false;

    public void StartListener() {

        image_RL.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                LogUtil.i("onTouch", motionEvent.getAction());
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        LogUtil.d("onTouch", "down");
                        mediaPlayerStop();
                        mAudioRecoderUtils.startRecord("20181220");
                        image.setImageResource(R.drawable.record_selector);
                        animationDrawable = new AnimationDrawable();
                        animationDrawable = (AnimationDrawable) image.getDrawable();
                        animationDrawable.start();
                        break;
                    case MotionEvent.ACTION_UP:
                        LogUtil.d("onTouch", "up");
                        if (animationDrawable != null) {
                            animationDrawable.stop();
                        }
                        image.setImageResource(R.drawable.item1);
                        mAudioRecoderUtils.stopRecord();
                        break;
                }
                return true;
            }
        });
//        //Button的touch监听
//        image.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (onclick) {
//
//                } else {
//
//
//                }
//            }
//        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.audioYes:
                mediaPlayerStop();
                startActivity(new Intent(RecordActivity.this, CorrectActivity.class));
                finish();
                break;
            case R.id.audioNo:
                mediaPlayerStop();
                startActivity(new Intent(RecordActivity.this, ErrorActivity.class));
                finish();
                break;
        }
    }

    @Override
    public void onCompleted(String url) {

    }

    @Override
    public void onError(Throwable e, String url) {
        LogUtil.i("tag", e.getMessage());
    }

    @Override
    public void onNext(ResponseBody responseBody, String url) {
        try {
            String json = responseBody.string();
            LogUtil.i("tag", json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
